﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using System.Runtime.InteropServices;

namespace Douban.Core.Interop
{
    public enum KeyState
    { 
        Normal = 0x00,
        Down = 0x01,
        Toggled = 0x02
    }

    public static class KeyHelper
    {
        private static ushort _highOrder = 0x8000;
        private static ushort _lowOrder = 0x0001;

        [DllImport("user32.dll")]
        private static extern ushort GetKeyState(int virtualKey);

        public static KeyState GetKeyState(Key key)
        {
            ushort keyState = GetKeyState(KeyInterop.VirtualKeyFromKey(key));
            KeyState returnKeyState = KeyState.Normal;

            if (IsKeyDown(keyState)) returnKeyState = KeyState.Down;
            if (IsKeyToggled(keyState)) returnKeyState |= KeyState.Toggled;

            return returnKeyState;
        }

        private static bool IsKeyDown(ushort keyState)
        {
            return (keyState & _highOrder) == _highOrder;
        }

        private static bool IsKeyToggled(ushort keyState)
        {
            return (keyState & _lowOrder) == _lowOrder;
        }
    }
}
